# v0.2-main.py 
import sys
import argparse
import re
import os 

#新增：莱文斯坦距离函数
def levenshtein_distance(s1, s2):
    """计算两个字符串之间的莱文斯坦编辑距离"""
    if len(s1) < len(s2):
        return levenshtein_distance(s2, s1)
    if len(s2) == 0:
        return len(s1)
    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row
    return previous_row[-1]

#基础功能函数
def count_chars(content):
    """统计字符数"""
    return len(content)

def count_words(content):
    """统计单词数（以空白字符分割）"""
    return len(content.split())

def count_sentences(content):
    """使用正则表达式统计句子数"""
    return len(re.findall(r'[.!?](?:\s|$)', content))

#主函数(升级了异常处理)
def main():
    parser = argparse.ArgumentParser(description="A command-line text counting tool (v0.2).")
    parser.add_argument('file', help="The path to the input text file.")
    parser.add_argument('-c', '--chars', action='store_true', help="Count the number of characters.")
    parser.add_argument('-w', '--words', action='store_true', help="Count the number of words.")
    parser.add_argument('-s', '--sentences', action='store_true', help="Count the number of sentences.")
    parser.add_argument('--all', action='store_true', help="Show all statistics.")
    args = parser.parse_args()

    try:
        with open(args.file, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
    except FileNotFoundError:
        #智能建议模块逻辑
        print(f"Error: File not found at {args.file}", file=sys.stderr)
        
        try:
            input_path = args.file
            input_dir = os.path.dirname(input_path)
            input_filename = os.path.basename(input_path)
            
            if not input_dir:
                input_dir = '.'

            if os.path.isdir(input_dir):
                best_match = None
                min_distance = float('inf')
                
                for filename in os.listdir(input_dir):
                    distance = levenshtein_distance(input_filename, filename)
                    if distance < min_distance:
                        min_distance = distance
                        best_match = filename
                
                if best_match and min_distance <= 3:
                    suggested_path = os.path.join(input_dir, best_match)
                    print(f"Did you mean: {suggested_path}?", file=sys.stderr)
        except Exception:
            pass # 如果寻找建议时出错，静默失败

        sys.exit(1)

    if args.all or args.chars:
        print(f"Characters: {count_chars(content)}")
    if args.all or args.words:
        print(f"Words: {count_words(content)}")
    if args.all or args.sentences:
        print(f"Sentences: {count_sentences(content)}")

    if not (args.all or args.chars or args.words or args.sentences):
        parser.print_help()

if __name__ == '__main__':
    main()